﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using System.Reflection;
using System.IO;
using System.Xml.Linq;
using BusinessEntities.Model;
using System.Xml.Serialization;
namespace DAL
{
    class EventsInitializer : DropCreateDatabaseAlways<EventsDB>
    {
        protected override void Seed(EventsDB context)
        {
            base.Seed(context);
            LoadCitiesFromXML(context);
            LoadUsersFromXML(context);
            LoadHallsFromXML(context);
        }

        public static void PubSeed(EventsDB context)
        {
            LoadCitiesFromXML(context);
            LoadUsersFromXML(context);
            LoadHallsFromXML(context);
        }


        private static void LoadCitiesFromXML(EventsDB context)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Stream reader = assembly.GetManifestResourceStream("DAL.cities.xml");
            XElement elem = XElement.Load(reader);
            foreach (var item in elem.Elements())
            {
                context.Cities.Add(new City() { Name = item.Value });
            }
            context.SaveChanges();
        }

        private static void LoadUsersFromXML(EventsDB context)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Stream reader = assembly.GetManifestResourceStream("DAL.users.xml");
            XmlRootAttribute r = new XmlRootAttribute("Users");
            XmlSerializer s = new XmlSerializer(typeof(List<User>), r);
            List<User> userList = (List<User>)s.Deserialize(reader);
            foreach (User item in userList)
            {
                context.Users.Add(item);
            }
            context.SaveChanges();
        }

        private static void LoadHallsFromXML(EventsDB context)
        {
            Assembly assembly = Assembly.GetExecutingAssembly();
            Stream reader = assembly.GetManifestResourceStream("DAL.halls.xml");
            XmlRootAttribute r = new XmlRootAttribute("Halls");
            XmlSerializer s = new XmlSerializer(typeof(List<Hall>), r);
            List<Hall> hallList = (List<Hall>)s.Deserialize(reader);
            foreach (Hall item in hallList)
            {
                City city = context.Cities.Find(item.CityID);
                item.City = city;
                context.Halls.Add(item);
            }
            context.SaveChanges();
        }
    }
}
